# -*- coding: utf-8 -*-
import os
import random
from operator import itemgetter

import cv2
import numpy as np
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH  # 设置对其方式
from docx.oxml.ns import qn  # 设置字体
from docx.shared import Pt  # 用来设置字体的大小

basedir = "./img/"


def read_img_2_list(img_path):
    # 读取图片
    img = cv2.imdecode(np.fromfile(img_path, dtype=np.uint8), -1)
    # 把图片转换为灰度模式
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).reshape(-1, 1)
    return [_[0] for _ in img.tolist()]


# 获取所有汉字的向量表示，以dict储存
def get_all_char_vectors():
    image_paths = [_ for _ in os.listdir(basedir) if _.endswith("png")]
    img_vector_dict = {}
    for image_path in image_paths:
        img_vector_dict[image_path[0]] = read_img_2_list(img_path=basedir + image_path)

    return img_vector_dict


# 计算两个向量之间的余弦相似度
def cosine_similarity(vector1, vector2):
    dot_product = 0.0
    normA = 0.0
    normB = 0.0
    for a, b in zip(vector1, vector2):
        dot_product += a * b
        normA += a**2
        normB += b**2
    if normA == 0.0 or normB == 0.0:
        return 0
    else:
        return dot_product / ((normA**0.5) * (normB**0.5))


if __name__ == "__main__":
    img_vector_dict = get_all_char_vectors()

    # 获取最接近的汉字
    similarity_dict = {}
    with open("./learn_words.txt", "r", encoding="utf-8") as f:
        words = f.read().strip()
    # words = "人 大 子 了 生 虫 云 山 十 八 禾 木 田 日 火 目 手 足 口 耳 上 下 土"
    for i in words.split(" "):
        match_char = i
        match_vector = img_vector_dict[match_char]
        for char, vector in img_vector_dict.items():
            cosine_similar = cosine_similarity(match_vector, vector)
            similarity_dict[char] = cosine_similar
        # 按相似度排序，取前10个
        sorted_similarity = sorted(
            similarity_dict.items(), key=itemgetter(1), reverse=True
        )
        # print(
        #     [
        #         (char, round(similarity, 4))
        #         for char, similarity in sorted_similarity[:10]
        #     ]
        # )
        chars = []
        for char, similarity in sorted_similarity[:10]:
            chars.append(char)
        print("========\n")
        sum_words = 104
        text = ""
        for j in range(sum_words):
            word = chars[random.randint(0, 9)]
            text += word + " "
        title = '请画出下面"%s"字' % i
        doc = Document()
        title1 = doc.add_heading(level=1)
        title1.alignment = WD_ALIGN_PARAGRAPH.CENTER
        title_run = title1.add_run(title)
        title_run.font.size = Pt(40)

        p = doc.add_paragraph()
        r = p.add_run(text)
        r.font.name = "宋体"
        r._element.rPr.rFonts.set(qn("w:eastAsia"), "宋体")
        r.font.size = Pt(36)
        doc.save("./words/" + title + ".docx")
        print(title + " 生成OK\n")
